package com.zyh.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.server.config.Constant;
import com.zyh.server.entity.User;
import com.zyh.server.mapper.UserMapper;
import com.zyh.server.service.UserService;
import com.zyh.server.utils.Md5Util;
import com.zyh.server.utils.R;
import com.zyh.server.utils.RedisUtil;
import com.zyh.server.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author ZYH
 * @description 针对表【t_user】的数据库操作Service实现
 * @createDate 2024-11-12 11:22:52
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisUtil redisUtil;


	/**
	 * service层用户登录方法
	 *
	 * @param loginVO
	 *
	 * @return
	 */
	@Override
	public R findUserByUsernameAndPassword(LoginVO loginVO) {
		// 将前端传入的加密过的密码进行二次加密
		loginVO.setPassword(Md5Util.backMd5(loginVO.getPassword()));
		User user = userMapper.selectUser(loginVO);
		return Objects.isNull(user) ? R.fail("登录失败，用户名或者密码错误！")
				: R.ok("登录成功！").setData(user);
	}


	/**
	 * 更新用户信息的方法
	 *
	 * @param user
	 *
	 * @return
	 */
	@Override
	public R modifyUserInfo(String token, User user) {
		Object obj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
		User redUser = new ObjectMapper().convertValue(obj, User.class);
		user.setId(redUser.getId());
		user.setPassword(Md5Util.backMd5(user.getPassword()));
		int i = userMapper.updateUserInfo(user);
		Boolean flag = false;
		if (i == 1) {
			// 从redis中删除token
			redisUtil.deleteObj(Constant.REDIS_TOKEN_PREFIX + token);
		}
		return i == 1 ? R.ok("更新用户信息成功！") : R.fail("更新用户信息失败！");
	}
}




